package com.wenwei.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jaeger.library.StatusBarUtil;
import com.jakewharton.rxbinding.widget.RxCheckedTextView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.orhanobut.logger.Logger;
import com.umeng.message.PushAgent;
import com.wenwei.bean.LoginBean;
import com.wenwei.bean.RegisterBean;
import com.wenwei.bean.ThreadUserInfo;
import com.wenwei.net.ApiManager;
import com.wenwei.net.BaseSubscriber;
import com.wenwei.parking.AtyContainer;
import com.wenwei.parking.BaseActivity;
import com.wenwei.parking.Constant;
import com.wenwei.parking.R;
import com.wenwei.utils.AccountValidatorUtil;
import com.wenwei.utils.RogerSPUtils;
import com.wenwei.utils.TimeCountUtil;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.functions.Func4;

/**
 * Created by Administrator on 2017/8/21.
 */
public class RegisterActivity extends BaseActivity {


    @Bind(R.id.base_title)
    TextView baseTitle;
    @Bind(R.id.phone_et)
    EditText phoneEt;
    @Bind(R.id.input_code)
    EditText inputCode;
    @Bind(R.id.register_get_code)
    TextView registerGetCode;
    @Bind(R.id.pw_et)
    EditText pwEt;
    @Bind(R.id.re_pw_et)
    EditText rePwEt;
    @Bind(R.id.login_btn)
    TextView loginBtn;
    @Bind(R.id.check_box)
    CheckBox checkBox;
    @Bind(R.id.register_tv)
    TextView registerTv;
    @Bind(R.id.new_pw_tag)
    TextView newPwTag;

    private String mActType = "";
    @Override
    public int setLayoutResourceId() {
        return R.layout.activity_register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void init() {
        super.init();
        mActType = getIntent().getStringExtra("type");
    }

    @Override
    protected void initView() {
        super.initView();

        if(mActType.equals("register")){
            baseTitle.setText("注册");
            loginBtn.setText("注册");
        }else if(mActType.equals("bind")){
            baseTitle.setText("绑定手机号");
            loginBtn.setText("绑定");
        }else{
            baseTitle.setText("忘记密码");
            loginBtn.setText("完成");
            newPwTag.setText("新密码");
        }

        Observable<CharSequence> phoneObservable = RxTextView.textChanges(phoneEt);
        Observable<CharSequence> psObservable = RxTextView.textChanges(pwEt);
        Observable<CharSequence> codeObservable = RxTextView.textChanges(inputCode);
        Observable<CharSequence> repsObservable = RxTextView.textChanges(rePwEt);
        Observable.combineLatest(phoneObservable, psObservable,codeObservable, repsObservable,new Func4<CharSequence, CharSequence,CharSequence,CharSequence, Boolean>() {
            @Override
            public Boolean call(CharSequence charSequence, CharSequence charSequence2, CharSequence charSequence3, CharSequence charSequence4) {
                return !charSequence.toString().equals("") && !charSequence2.toString().equals("")&& !charSequence3.toString().equals("")&& !charSequence4.toString().equals("");
            }
        }).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean aBoolean) {
                loginBtn.setEnabled(aBoolean);
                if(aBoolean){
                    loginBtn.setBackgroundResource(R.drawable.button_state_2);
                }else{
                    loginBtn.setBackgroundResource(R.drawable.button_state_1);
                }
            }
        });
    }


    @OnClick({R.id.register_tv,R.id.base_back, R.id.register_get_code, R.id.login_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.register_tv:
                Bundle b = new Bundle();
                b.putInt("type", Constant.TEXT_TYPE_REGISTER);
                goActivity(mContext,ActivityTv.class,b);
                break;
            case R.id.base_back:
                finish();
                break;
            case R.id.register_get_code:
                if (AccountValidatorUtil.isMobile(phoneEt.getText().toString())){
                    getRegisterSmsCode(phoneEt.getText().toString());
                }else {
                    showToast("手机号格式错误");
                }
                break;
            case R.id.login_btn:
                if (!AccountValidatorUtil.isMobile(phoneEt.getText().toString())){
                    showToast("手机号格式错误");
                    return;
                }
                if(!pwEt.getText().toString().equals(rePwEt.getText().toString())){
                    showToast("请再次确认密码一致");
                    return;
                }
                if(mActType.equals("bind")){
                    bindInfo();
                }else {
                    if(checkBox.isChecked()){
                        registerUser();
                    }else {
                        showToast("请还未同意用户协议");
                    }

                }
                break;
        }
    }

    //绑定资料
    private BaseSubscriber<Object> bindSb;
    private void bindInfo(){
        bindSb = new BaseSubscriber<Object>(mContext) {
            @Override
            public void onSuccess(Object o) {
                userLogin();
            }
        };
        ThreadUserInfo info = (ThreadUserInfo) getIntent().getSerializableExtra("bean");
        ApiManager.getInstance().bindInfo(bindSb,getIntent().getStringExtra("uid"),
                phoneEt.getText().toString(),pwEt.getText().toString(),inputCode.getText().toString(),
                info.getNikename(),info.getAvator(),info.getRegistrationId(),info.getPlatform());
    }




    //获取验证码
    private BaseSubscriber<Object> smsSubscriber;
    private void getRegisterSmsCode(String phone){
        smsSubscriber = new BaseSubscriber<Object>(mContext,true,"获取验证码...") {
            @Override
            public void onSuccess(Object o) {
                showToast("验证码发送成功");
                TimeCountUtil timeCountUtil = new TimeCountUtil( (Activity)mContext,60000,1000,registerGetCode);
                timeCountUtil.start();
            }
        };
        if(mActType.equals("register")||mActType.equals("bind")){
            ApiManager.getInstance().getRegisterSmsCode(smsSubscriber,phone);
        }else {
            ApiManager.getInstance().getForgetSmsCode(smsSubscriber,phone);
        }

    }

    //注册(重置密码）
    private BaseSubscriber<RegisterBean> registerSubscriber;
    private void registerUser(){
        registerSubscriber = new BaseSubscriber<RegisterBean>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(RegisterBean registerBean) {
                if(mActType.equals("register")){
                    userLogin();
                }else {
                    showToast("重置成功，立即登录");
                    AtyContainer.getInstance().finishAllActivity();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                goActivity(mContext,LoginActivity.class);
                            } catch (Exception e) {
                            }
                        }
                    }).start();
                }
            }
        };
        try{
            JSONObject jb = new JSONObject();
            jb.put("username",phoneEt.getText().toString());
            jb.put("password",pwEt.getText().toString());
            jb.put("verifyCode",inputCode.getText().toString());
            if(mActType.equals("register")){
                ApiManager.getInstance().userRegister(registerSubscriber,jb.toString());
            }else {
                ApiManager.getInstance().userReSetPassWord(registerSubscriber,jb.toString());
            }
        }catch (Exception e){

        }
    }


    BaseSubscriber<LoginBean> loginSubscriber;
    private void userLogin(){
        String userPhone = phoneEt.getText().toString();
        String userPw = pwEt.getText().toString();
        loginSubscriber = new BaseSubscriber<LoginBean>(mContext,true,"请稍后...") {
            @Override
            public void onSuccess(LoginBean s) {
                showToast("注册成功，立即体验吧");
                RogerSPUtils.putObject(mContext, Constant.SP_USER_LOGIN_RESULT,s);
                AtyContainer.getInstance().finishAllActivity();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            goActivity(mContext,HostActivity.class);
                        } catch (Exception e) {
                        }
                    }
                }).start();
            }
        };
        PushAgent m = PushAgent.getInstance(mContext);
        Logger.d("token:"+m.getRegistrationId());
        ApiManager.getInstance().userLogin(loginSubscriber, userPhone, userPw, m.getRegistrationId());
    }

}
